import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

class PushService extends GetxService {
  late JPush jpush;
  static PushService get instance => PushService();

  init() async {
    jpush = JPush();
    addEventHandler();

    ///配置应用 Key
    jpush.setup(
      appKey: "b4b722ba984f4d9b61faee4a",
      channel: "developer-default",
      production: false,
      debug: false,
    );
    jpush.applyPushAuthority(
      const NotificationSettingsIOS(sound: true, alert: true, badge: true),
    );
    bindRegistrationId();
    jpush.setAlias('u${AuthService.instance.user.id}');
    jpush.setBadge(0);
  }

  bindRegistrationId() async {
    Http.instance.post(
      '/plugin/j_push/api/bindRegistrationId',
      data: {
        'registration_id': await jpush.getRegistrationID(),
      },
    );
  }

  static Future unbindRegistrationId() async {
    await Http.instance.post('/plugin/j_push/api/unbindRegistrationId');
  }

  addEventHandler() {
    try {
      jpush.addEventHandler(
          onReceiveNotification: (Map<String, dynamic> message) async {},
          onOpenNotification: (Map<String, dynamic> message) async {
            messageEvent(message);
          },
          onInAppMessageClick: (Map<String, dynamic> message) async {
            messageEvent(message);
          },
          onReceiveMessage: (Map<String, dynamic> message) async {},
          onReceiveNotificationAuthorization:
              (Map<String, dynamic> message) async {});
    } on PlatformException {
      debugPrint('Failed to get platform version.');
    }
  }

  messageEvent(message) {
    print(message);
    var data = Platform.isIOS
        ? message["extras"]
        : jsonDecode(message["extras"]["cn.jpush.android.EXTRA"]);

    var url = data?['url'];
    if (url != null) {
      App.push(url);
    }
    jpush.setBadge(0);
  }
}
